<template>
  <div class="alert-report-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Document /></el-icon>
            预警统计报表
          </span>
          <el-text size="small" type="danger" style="font-size: 12px;">
            不选择时间范围时，默认显示最近30天的数据
          </el-text>
        </div>
      </template>

      <!-- 报表筛选 -->
      <div class="filter-bar">
        <el-form :model="reportFilters" inline>

          <el-form-item label="时间范围">

            <div style="display: flex; flex-direction: column; gap: 5px;">
              <el-date-picker
                v-model="reportFilters.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 300px"
                clearable
              />

            </div>
          </el-form-item>
          <el-form-item label="预警类型">
            <el-select
              v-model="reportFilters.alertType"
              placeholder="选择预警类型"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value="" />
<!--              <el-option label="行为异常" value="behavior" />-->
<!--              <el-option label="安全违规" value="security" />-->
<!--              <el-option label="离线预警" value="offline" />-->
<!--              <el-option label="预警" value="offline" />-->
              <el-option label="安全预警" value="security" />
              <el-option label="网络预警" value="network" />
              <el-option label="流量预警" value="traffic" />
              <el-option label="离线预警" value="offline" />

              <el-option label="行为预警" value="behavior" />
            </el-select>
          </el-form-item>
          <el-form-item label="分组方式">
            <el-select
              v-model="reportFilters.groupBy"
              placeholder="选择分组方式"
              style="width: 150px"
            >
              <el-option label="按类型" value="type" />
              <el-option label="按日期" value="date" />
              <el-option label="按客户端" value="client" />
              <el-option label="按严重程度" value="severity" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadReportData">
              <el-icon><Search /></el-icon>
              生成统计
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计概览 -->
      <div class="stats-overview">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card">
              <div class="stat-number">{{ reportStats.totalAlerts }}</div>
              <div class="stat-label">总预警数</div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card">
              <div class="stat-number">{{ reportStats.resolvedAlerts }}</div>
              <div class="stat-label">已处理</div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card">
              <div class="stat-number">{{ reportStats.pendingAlerts }}</div>
              <div class="stat-label">待处理</div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card">
              <div class="stat-number">{{ reportStats.avgResponseTime }}</div>
              <div class="stat-label">平均响应时间(分钟)</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 预警类型分布图表 -->
      <div class="charts-container">
        <el-row :gutter="20">
          <el-col :xs="24" :lg="24">
            <div class="chart-card">
              <h3>预警类型分布</h3>
              <div class="type-distribution" v-loading="loading">
                <div v-if="reportData && reportData.length > 0" class="distribution-bars">
                  <div
                    v-for="item in reportData"
                    :key="item.category"
                    class="distribution-item"
                  >
                    <div class="item-header">
                      <el-tag :type="getCategoryTagType(item.category)" size="small">
                        {{ getDisplayCategoryName(item.category) }}
                      </el-tag>
                      <span class="item-count">{{ item.count }}个</span>
                      <span class="item-percentage">{{ item.percentage }}%</span>
                    </div>
                    <div class="item-bar">
                      <div
                        class="item-fill"
                        :style="{
                          width: item.percentage + '%',
                          backgroundColor: getBarColor(item.category)
                        }"
                      ></div>
                    </div>
                    <div class="item-details">
                      <span class="resolved">已处理: {{ item.resolved }}</span>
                      <span class="pending">待处理: {{ item.pending }}</span>
                    </div>
                  </div>
                </div>
                <div v-else class="no-data">
                  <el-empty description="暂无数据" />
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 详细数据表格 -->
      <div class="report-table">
        <div class="table-header">
          <h3>详细统计数据</h3>
        </div>
        <el-table :data="alertList" stripe style="width: 100%" v-loading="loading">
          <el-table-column prop="type" label="分类" width="120">
            <template #default="{ row }">
              <el-tag :type="getAlertTypeColor(row.type, row.subtype)" size="small">
                {{ getAlertTypeName(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="subtype" label="子类型" width="150">
            <template #default="{ row }">
              <span>{{ getAlertTypeName(row.type, row.subtype) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="client_name" label="客户端" width="150">
            <template #default="{ row }">
              <span>{{ row.client_name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="severity" label="严重程度" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getSeverityTagType(row.severity)" size="small">
                {{ getSeverityText(row.severity) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="200">
            <template #default="{ row }">
              <span>{{ row.title }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="resolved" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.resolved ? 'success' : 'warning'" size="small">
                {{ row.resolved ? '已处理' : '待处理' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180" align="center">
            <template #default="{ row }">
              <span>{{ formatDateTime(row.created_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button size="small" type="text" @click="viewDetails(row)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 预警详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        :title="selectedCategory + ' - 详细信息'"
        width="60%"
        :before-close="handleDetailClose"
      >
        <div class="detail-content" v-if="selectedCategoryDetail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="预警类型">
              <el-tag :type="getCategoryTagType(selectedCategoryDetail.category)">
                {{ selectedCategoryDetail.category }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="总数量">
              {{ selectedCategoryDetail.count }}
            </el-descriptions-item>
            <el-descriptions-item label="占比">
              {{ selectedCategoryDetail.percentage }}%
            </el-descriptions-item>
            <el-descriptions-item label="已处理">
              {{ selectedCategoryDetail.resolved }}
            </el-descriptions-item>
            <el-descriptions-item label="待处理">
              {{ selectedCategoryDetail.pending }}
            </el-descriptions-item>
            <el-descriptions-item label="平均响应时间">
              {{ selectedCategoryDetail.avgResponseTime }} 分钟
            </el-descriptions-item>
          </el-descriptions>

          <div class="detail-chart" style="margin-top: 20px;">
            <h4>处理状态分布</h4>
            <div class="status-chart">
              <div class="status-item resolved">
                <div class="status-bar" :style="{ width: (selectedCategoryDetail.resolved / selectedCategoryDetail.count * 100) + '%' }"></div>
                <span class="status-label">已处理: {{ selectedCategoryDetail.resolved }}</span>
              </div>
              <div class="status-item pending">
                <div class="status-bar" :style="{ width: (selectedCategoryDetail.pending / selectedCategoryDetail.count * 100) + '%' }"></div>
                <span class="status-label">待处理: {{ selectedCategoryDetail.pending }}</span>
              </div>
            </div>
          </div>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Document, Search, View
} from '@element-plus/icons-vue'
import { alertsAPI } from '@/services/api'
import { getAlertTypeName, getAlertTypeColor } from '@/config/app.js'

// 响应式数据
const loading = ref(false)

// 报表筛选器
const reportFilters = reactive({
  dateRange: [],
  alertType: '',
  groupBy: 'type'
})

// 统计概览数据
const reportStats = reactive({
  totalAlerts: 0,
  resolvedAlerts: 0,
  pendingAlerts: 0,
  avgResponseTime: 0
})

// 报表数据
const reportData = ref([])

// 预警列表数据
const alertList = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const selectedCategory = ref('')
const selectedCategoryDetail = ref(null)

// 方法
const loadReportData = async () => {
  loading.value = true

  try {
    // 构建报表请求参数
    const reportParams = {
      groupBy: reportFilters.groupBy
    }

    // 构建预警列表请求参数
    const alertParams = {
      page: 1,
      size: 100 // 获取更多数据用于展示
    }

    // 添加日期范围
    if (reportFilters.dateRange && reportFilters.dateRange.length === 2) {
      reportParams.startDate = reportFilters.dateRange[0]
      reportParams.endDate = reportFilters.dateRange[1]
      // 为预警列表API构造正确的日期时间格式
      const startDateTime = `${reportFilters.dateRange[0]} 00:00:00`
      const endDateTime = `${reportFilters.dateRange[1]} 23:59:59`
      alertParams.dateRange = `${startDateTime},${endDateTime}`
    }

    // 添加预警类型过滤
    if (reportFilters.alertType) {
      reportParams.alertType = reportFilters.alertType
      alertParams.type = reportFilters.alertType
    }

    // 并行调用API获取报表数据和预警列表
    const [reportResponse, alertResponse] = await Promise.all([
      alertsAPI.getAlertReportData(reportParams),
      alertsAPI.getAlerts(alertParams)
    ])

    if (reportResponse.code === 200 && reportResponse.data) {
      // 更新统计概览
      const stats = reportResponse.data.stats
      Object.assign(reportStats, {
        totalAlerts: stats.totalAlerts,
        resolvedAlerts: stats.resolvedAlerts,
        pendingAlerts: stats.pendingAlerts,
        avgResponseTime: stats.avgResponseTime
      })

      // 更新详细数据
      reportData.value = reportResponse.data.reportData || []
    }

    if (alertResponse.code === 200 && alertResponse.data) {
      // 更新预警列表
      alertList.value = alertResponse.data.list || []
    }

    ElMessage.success('报表数据加载完成')
  } catch (error) {
    console.error('获取报表数据失败:', error)
    ElMessage.error('获取报表数据失败')
  } finally {
    loading.value = false
  }
}







// 获取分类显示名称（兼容后端返回的中文名称和英文类型）
const getDisplayCategoryName = (category) => {
  // 如果已经是中文名称，直接返回
  if (category && (category.includes('异常') || category.includes('违规') || category.includes('预警') || category.includes('超时'))) {
    return category
  }

  // 否则使用映射函数转换
  return getAlertTypeName(category)
}

const getCategoryTagType = (category) => {
  const typeMap = {
    // 中文映射（用于分组统计）
    '行为异常': 'warning',
    '安全违规': 'danger',
    '离线预警': 'danger',
    '心跳超时': 'danger',
    '未授权软件': 'danger',
    '键盘鼠标活动异常': 'warning',
    'USB设备违规': 'danger',
    '过度空闲': 'info',
    // 原始类型映射（用于预警列表）
    'behavior': 'warning',
    'security': 'danger',
    'offline': 'danger'
  }

  // 如果是中文名称，直接查找
  if (typeMap[category]) {
    return typeMap[category]
  }

  // 否则使用新的颜色映射函数
  return getAlertTypeColor(category)
}

const getBarColor = (category) => {
  const colorMap = {
    '行为异常': '#E6A23C',
    '安全违规': '#F56C6C',
    '离线预警': '#F56C6C',
    '心跳超时': '#F56C6C',
    '未授权软件': '#F56C6C',
    '键盘鼠标活动异常': '#E6A23C',
    'USB设备违规': '#F56C6C',
    '过度空闲': '#909399'
  }
  return colorMap[category] || '#409EFF'
}

// 严重程度标签类型
const getSeverityTagType = (severity) => {
  const severityMap = {
    1: 'info',    // 低
    2: 'warning', // 中
    3: 'danger'   // 高
  }
  return severityMap[severity] || 'info'
}

// 严重程度文本
const getSeverityText = (severity) => {
  const severityMap = {
    1: '低',
    2: '中',
    3: '高'
  }
  return severityMap[severity] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const viewDetails = (row) => {
  selectedCategory.value = row.category
  selectedCategoryDetail.value = row
  detailDialogVisible.value = true
}

const handleDetailClose = () => {
  detailDialogVisible.value = false
  selectedCategory.value = ''
  selectedCategoryDetail.value = null
}



// 生命周期
onMounted(() => {
  // 设置默认时间范围为最近7天
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 7)

  reportFilters.dateRange = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]

  loadReportData()
})
</script>

<style scoped>
.alert-report-page {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stats-overview {
  margin-bottom: 30px;
}

.stat-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.charts-container {
  margin-bottom: 30px;
}

.chart-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.chart-card h3 {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: #303133;
}

/* 类型分布图表样式 */
.type-distribution {
  background: #fff;
  border-radius: 6px;
  padding: 20px;
  min-height: 200px;
}

.distribution-bars {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.distribution-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.distribution-item:hover {
  background: #f0f9ff;
  border-color: #409EFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.item-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.item-count {
  font-weight: 600;
  color: #303133;
}

.item-percentage {
  font-weight: 600;
  color: #409EFF;
}

.item-bar {
  height: 8px;
  background: #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.item-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.6s ease;
}

.item-details {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.item-details .resolved {
  color: #67C23A;
}

.item-details .pending {
  color: #E6A23C;
}

.no-data {
  text-align: center;
  padding: 40px;
}

/* 严重程度分布图样式 */
.severity-chart {
  padding: 20px;
}

.severity-bars {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.severity-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.severity-label {
  width: 60px;
  font-size: 14px;
  color: #303133;
  text-align: right;
}

.severity-bar {
  flex: 1;
  height: 20px;
  background: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
  position: relative;
}

.severity-fill {
  height: 100%;
  border-radius: 10px;
  transition: width 0.3s ease;
}

.severity-fill.critical {
  background: linear-gradient(90deg, #F56C6C, #F78989);
}

.severity-fill.urgent {
  background: linear-gradient(90deg, #E6A23C, #EEBE77);
}

.severity-fill.high {
  background: linear-gradient(90deg, #409EFF, #79BBFF);
}

.severity-fill.medium {
  background: linear-gradient(90deg, #67C23A, #95D475);
}

.severity-fill.low {
  background: linear-gradient(90deg, #909399, #B1B3B8);
}

.severity-value {
  width: 50px;
  font-size: 14px;
  color: #303133;
  font-weight: 600;
}

.report-table {
  margin-top: 30px;
}

.table-header {
  margin-bottom: 20px;
}

.table-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

/* 表格内容样式 */
.count-number {
  font-weight: 600;
  color: #409EFF;
}

.percentage-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.percentage-bar {
  width: 60px;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.percentage-fill {
  height: 100%;
  background: linear-gradient(90deg, #409EFF, #79BBFF);
  border-radius: 3px;
  transition: width 0.3s ease;
}

.percentage-text {
  font-size: 12px;
  color: #303133;
  font-weight: 600;
}

.resolved-count {
  color: #67C23A;
  font-weight: 600;
}

.no-pending {
  color: #909399;
}

.response-time {
  display: flex;
  align-items: center;
  gap: 5px;
  justify-content: center;
  color: #606266;
}

/* 详情对话框样式 */
.detail-content {
  padding: 10px 0;
}

.detail-chart h4 {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #303133;
}

.status-chart {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-item.resolved .status-bar {
  background: linear-gradient(90deg, #67C23A, #95D475);
}

.status-item.pending .status-bar {
  background: linear-gradient(90deg, #E6A23C, #EEBE77);
}

.status-bar {
  height: 20px;
  border-radius: 10px;
  min-width: 20px;
  transition: width 0.3s ease;
}

.status-label {
  font-size: 14px;
  color: #303133;
  min-width: 100px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .stat-number {
    font-size: 24px;
  }

  .chart-placeholder {
    height: 200px;
  }

  .chart-icon {
    font-size: 32px;
  }
}
</style>
